﻿using DiLe.Mes.Application.Common;
using DiLe.Mes.Model.Common.Organization.Entity;
using DiLe.Mes.Model.Common.System.Entity;

namespace DiLe.Mes.Cloud.Controllers.SystemManage.SystemSetting {
    /// <summary>
    /// 班组
    /// </summary>
    [ApiExplorerSettings(GroupName = ApiCloudGroupConst.System)]
    public class TeamController : ApiBaseController {
        /// <summary>
        /// 
        /// </summary>
        private readonly SystemClient _systemClient;
        private readonly OrganizationClient _organizationClient;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="systemClient"></param>
        /// <param name="organizationClient"></param>
        public TeamController(SystemClient systemClient, OrganizationClient organizationClient) {
            _systemClient = systemClient;
            _organizationClient = organizationClient;
        }

        /// <summary>
        /// 获取班组信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetTeamList(QueryParameter parameter) {
            var whereExpression = Expressionable.Create<TeamEntity>();
            if (!parameter.Keyword.IsNullOrEmpty()) {
                whereExpression.Or(p => p.Name.Contains(parameter.Keyword));
                whereExpression.Or(p => p.Code.Contains(parameter.Keyword));
            }
            if (parameter.Pagination == null) {
                var res = await _systemClient.GetTeamListAsync(whereExpression.ToExpression());
                await FillTeamExjosn(res);
                return Success(res);
            } else {
                var res = await _systemClient.GetTeamPageListAsync(whereExpression.ToExpression(), parameter.Pagination);
                await FillTeamExjosn(res.Record);
                return Success(res);
            }
        }
        /// <summary>
        /// 获取班组信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetTeamInfo(long id) {
            var res = await _systemClient.GetTeamInfoAsync(id);
            await FillTeamExjosn(new List<TeamEntity> { res });
            return Success(res);
        }
        /// <summary>
        /// 保存班组信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SaveTeam(TeamEntity entity) {
            var res = await _systemClient.SaveTeamAsync(entity);
            return res ? Success() : Fail();
        }
        /// <summary>
        /// 删除班组信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> DeleteTeam(List<long> ids) {
            var res = await _systemClient.DeleteTeamAsync(ids);
            return res ? Success() : Fail();
        }
        /// <summary>
        /// 更新班组状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UpdateTeamStatus(CommomParameter parameter) {
            var res = await _systemClient.UpdateTeamStatusAsync(parameter.Ids, parameter.Status);
            return Success(res);
        }

        #region 
        /// <summary>
        /// 填充班组额外的数据
        /// </summary>
        /// <param name="dataList"></param>
        private async Task FillTeamExjosn(List<TeamEntity> dataList) {
            if (!dataList.Any()) {
                return;
            }
            var userids = dataList.Select(p => p.Manager).ToList();
            var maps = new List<(long id, List<long> memberIds)>();
            foreach (var data in dataList) {
                if (data.Members.IsNullOrEmpty()) {
                    continue;
                }
                var arr = data.Members!.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                var temps = arr.ConvertAll(p => p.ToLong());
                userids.AddRange(temps);
                maps.Add((data.Id, temps));
            }
            userids = userids.Distinct().ToList();
            var userList = await _organizationClient.GetUserListByIdAsync(userids);
            foreach (var item in dataList) {
                var manager = userList?.FirstOrDefault(p => p.Id == item.Manager);
                item.ExtJson.Add("ManagerName", manager?.Name);

                var tempIds = maps.FirstOrDefault(x => x.id == item.Id).memberIds.ToList();
                var members = userList?.Where(p => tempIds.Contains(p.Id)).ToList() ?? new List<UserEntity>();
                item.ExtJson.Add("MemberNames", string.Join(",", members.ConvertAll(x => x.Name)));
            }
        }
        #endregion


    }
}
